package org.makcro.sms.services.chat.web.server.services;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dozer.Mapper;
import org.makcro.sms.services.chat.model.Subscriber;
import org.makcro.sms.services.chat.web.client.services.subscriber.SubscriberService;
import org.makcro.sms.services.chat.web.shared.dto.SubscriberDto;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;

public class SubscriberServiceFacade implements SubscriberService {

	private Logger															logger	= Logger.getLogger( SubscriberServiceFacade.class );

	private org.makcro.sms.services.chat.base.business.SubscriberService	subscriberService;
	
	private Mapper mapper;

	@Override
	public PagingLoadResult<SubscriberDto> search(PagingLoadConfig loadConfig) {

		// extract paging params
		int offset = loadConfig.getOffset();
		int limit = loadConfig.getLimit();

		// load paging data
		List<Subscriber> subscribers = this.subscriberService.search( new int[] { offset, limit } );
		Long count = this.subscriberService.getSearchCount();
		
		// convert to dto
		List<SubscriberDto> dtoMessages = new ArrayList<SubscriberDto>( subscribers.size() );
		
		for (Subscriber bulkMessage : subscribers) {
			SubscriberDto bulkMessageDto = this.mapper.map( bulkMessage, SubscriberDto.class );
			dtoMessages.add( bulkMessageDto );
		}
		PagingLoadResult<SubscriberDto> loadResult = new BasePagingLoadResult<SubscriberDto>( dtoMessages, offset, (int)Math.min( Integer.MAX_VALUE, count ) );
		return loadResult;
	}

	public void setSubscriberService(org.makcro.sms.services.chat.base.business.SubscriberService subscriberService) {
		this.subscriberService = subscriberService;
	}

	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}
}
